package com.hmall.trade.mq.listeners;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.domain.MultiDelayCheckMsg;
import com.hmall.common.mq.handler.DelayMsgMessagePostProcessor;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import static com.hmall.common.constants.MqConstants.*;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/6/9 10:22
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class MqListener {
    private final IOrderService orderService;
    private final RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "mark.order.pay.queue",durable = "true"),
            exchange = @Exchange(name = "pay.topic",type = ExchangeTypes.TOPIC),
            key = {"pay.success"}
    ))
    public void payQueueListener(Long orderId) {
        log.warn("接受到支付消息，订单ID：{}",orderId);
        Order order = orderService.getById(orderId);
        //1、判断订单是否存在（不存在） 或者 状态是否为未支付（不为未支付）, 如果是其中任何一种情况，直接结束
        if(ObjectUtil.isEmpty(order) || order.getStatus() != 1){
            return;
        }
        orderService.markOrderPaySuccess(orderId);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TRADE_ORDER_DELAY_CHECK_QUEUE,durable = "true"),
            exchange = @Exchange(name = TRADE_ORDER_EXCHANGE,type = ExchangeTypes.TOPIC,delayed = "true"),
            key = TRADE_ORDER_DELAY_CHECK_KEY
    ))
    public void orderStatusDelayCheckListener(MultiDelayCheckMsg<Long> msg) {
        log.warn("接受支付状态检测的延时消息，订单ID：{}",msg.getCoreMsgData());
        Order order = orderService.getById(msg.getCoreMsgData());
        //1、判断订单状态是否为已支付，如果是，则不作处理了
        if(ObjectUtil.isEmpty(order) || order.getStatus() == 2){
            return;
        }
        //2、判断该笔订单的支付单是否是已支付，如果是已支付，则不作处理了
        if(isPay(msg.getCoreMsgData())){
            return;
        }

        // 3、检测是否还存在延时时间，如果有，继续取时间发延时消息
        if(msg.haveNextDelayTime()){
            rabbitTemplate.convertAndSend(TRADE_ORDER_EXCHANGE, TRADE_ORDER_DELAY_CHECK_KEY, msg, new DelayMsgMessagePostProcessor(msg.nextDelayTime()));
            return;
        }

        // 3、取消订单：订单状态修改为已取消
        orderService.cacelOrder(msg.getCoreMsgData());

    }

    private boolean isPay(Long id) {
        // 1、远程调用支付微服务，查询支付单交易状态
        // boolean isPay = payClient.queryPayOrderStatus(id);

        // 2、判断状态是否为已支付，如果是，则需要修改订单状态为已支付

        // 3、返回支付单交易状态
        return false;
    }
}
